package com.example.studentknowledge.service;

import com.example.studentknowledge.entity.Article;
import com.example.studentknowledge.entity.Comment;
import com.example.studentknowledge.entity.User;
import com.example.studentknowledge.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * 评论服务类
 */
@Service
@Transactional
public class CommentService {
    
    @Autowired
    private CommentRepository commentRepository;
    
    @Autowired
    private ArticleService articleService;
    
    @Autowired
    private PointService pointService;
    
    /**
     * 创建评论
     */
    public Comment createComment(Comment comment) {
        Comment savedComment = commentRepository.save(comment);
        
        // 更新文章评论数
        articleService.updateCommentCount(comment.getArticle().getId());
        
        // 给评论用户奖励积分
        pointService.rewardForComment(comment.getUser(), savedComment.getId());
        
        return savedComment;
    }
    
    /**
     * 更新评论
     */
    public Comment updateComment(Comment comment) {
        Comment existingComment = commentRepository.findById(comment.getId())
                .orElseThrow(() -> new RuntimeException("评论不存在"));
        
        return commentRepository.save(comment);
    }
    
    /**
     * 根据ID查找评论
     */
    public Optional<Comment> findById(Long id) {
        return commentRepository.findById(id);
    }
    
    /**
     * 删除评论
     */
    public void deleteComment(Long id) {
        Comment comment = commentRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("评论不存在"));
        
        commentRepository.deleteById(id);
        
        // 更新文章评论数
        articleService.updateCommentCount(comment.getArticle().getId());
    }
    
    /**
     * 根据文章获取评论
     */
    public Page<Comment> getCommentsByArticle(Article article, Pageable pageable) {
        return commentRepository.findByArticleOrderByCreatedAtDesc(article, pageable);
    }
    
    /**
     * 根据用户获取评论
     */
    public Page<Comment> getCommentsByUser(User user, Pageable pageable) {
        return commentRepository.findByUserOrderByCreatedAtDesc(user, pageable);
    }
    
    /**
     * 获取文章的顶级评论（非回复）
     */
    public List<Comment> getTopLevelComments(Article article) {
        return commentRepository.findTopLevelCommentsByArticle(article);
    }
    
    /**
     * 获取评论的回复
     */
    public List<Comment> getReplies(Comment parent) {
        return commentRepository.findByParentOrderByCreatedAtAsc(parent);
    }
    
    /**
     * 搜索评论
     */
    public Page<Comment> searchComments(String keyword, Pageable pageable) {
        return commentRepository.findByContentContaining(keyword, pageable);
    }
    
    /**
     * 获取最新评论
     */
    public List<Comment> getLatestComments(int limit) {
        return commentRepository.findLatestComments(Pageable.ofSize(limit));
    }
    
    /**
     * 统计文章的评论数
     */
    public Long countByArticle(Article article) {
        return commentRepository.countByArticle(article);
    }
    
    /**
     * 统计用户的评论数
     */
    public Long countByUser(User user) {
        return commentRepository.countByUser(user);
    }
    
    /**
     * 检查用户是否有权限编辑评论
     */
    public boolean canEditComment(Comment comment, User user) {
        // 管理员可以编辑所有评论
        if (user.getRole() == User.Role.ADMIN) {
            return true;
        }
        
        // 用户可以编辑自己的评论
        return comment.getUser().getId().equals(user.getId());
    }
    
    /**
     * 检查用户是否有权限删除评论
     */
    public boolean canDeleteComment(Comment comment, User user) {
        return canEditComment(comment, user);
    }
}